<template>
  <div class="task-detail-dialog-container">
    <el-dialog title="任务详情" v-model="state.isShowDialog" width="700px">
      <div v-if="state.task" class="task-detail">
        <div class="task-header">
          <span class="label">任务标题：</span>
          <h2>{{ state.task.title }}</h2>
          <span class="label">任务状态：</span>
          <el-tag :type="getStatusType(state.task.status)">{{ getStatusText(state.task.status) }}</el-tag>
        </div>

        <div class="task-info">
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span>{{ formatDate(state.task.created_at) }}</span>
          </div>
          <div class="info-item">
            <span class="label">更新时间：</span>
            <span>{{ formatDate(state.task.updated_at) }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建者：</span>
            <span>{{ getUserName(state.task.creator_id) }}</span>
          </div>
          <div class="info-item">
            <span class="label">分配学生：</span>
            <span>{{ getUserName(state.task.assignee_id) }}</span>
          </div>
        </div>

        <div class="task-description">
          <div class="section-title">任务描述</div>
          <div class="content">{{ state.task.description }}</div>
        </div>

        <div class="task-files">
          <div class="section-title">相关文件</div>
          <div class="file-list">
            <div class="file-item" v-if="state.task.taskfile">
              <el-icon><Document /></el-icon>
              <span class="file-name">{{ getFileName(state.task.taskfile) }}</span>
              <el-button type="primary" link @click="downloadFile('task')">下载</el-button>
            </div>
            <div v-if="!state.task.taskfile && !state.task.resultfile" class="no-files">
              暂无相关文件
            </div>
          </div>
        </div>
        <div class="task-files">
          <div class="section-title">结果文件</div>
          <div class="file-list">
            <div class="file-item" v-if="state.task.resultfile">
              <el-icon><UploadFilled /></el-icon>
              <span class="file-name">{{ getFileName(state.task.resultfile) }}</span>
              <el-button type="success" link @click="downloadFile('result')">下载</el-button>
            </div>
            <div v-if="!state.task.taskfile && !state.task.resultfile" class="no-files">
              暂无相关文件
            </div>
          </div>
        </div>

        <div class="task-operations">
          <div class="section-title">操作记录</div>
          <el-timeline>
            <el-timeline-item
              v-for="(operation, index) in state.operations"
              :key="index"
              :timestamp="formatDate(operation.operationTime)"
              :type="getOperationIconType(operation)"
            >
              <div class="operation-content">
                <span class="operator">{{ operation.operatorName }}</span>
                <span>{{ operation.operationContent }}</span>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
        <el-button @click="closeDialog" size="default">关 闭</el-button>
      </div>


    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="taskDetailDialog">
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { Document, UploadFilled } from '@element-plus/icons-vue';
import { getTaskDetail, downloadTaskFile } from "./task";
import Axios from "@/utils/Axios";

// 定义变量内容
const state = reactive({
  isShowDialog: false,
  task: null,
  operations: [],
  users: []
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 获取用户名
const getUserName = (userId) => {
  const user = state.users.find(u => u.user.id === userId);
  return user ? user.user.name : userId;
};

// 获取文件名
const getFileName = (filePath) => {
  if (!filePath) return "";
  return filePath.match(/[^/]+$/)[0];
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return "info";
    case 2: return "warning";
    case 3: return "success";
    case 4: return "danger";
    default: return "info";
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return "未提交";
    case 1: return "已删除";
    case 2: return "待审核";
    case 3: return "已通过";
    case 4: return "未通过";
    default: return "未知状态";
  }
};

// 获取操作图标类型
const getOperationIconType = (operation) => {
  const content = operation.operationContent;
  if (content.includes("创建")) return "primary";
  if (content.includes("更新")) return "info";
  if (content.includes("提交")) return "warning";
  if (content.includes("通过")) return "success";
  if (content.includes("不通过")) return "danger";
  if (content.includes("删除")) return "danger";
  return "";
};

// 下载文件
const downloadFile = (fileType) => {
  if (!state.task) return;

  const fileName = fileType === 'task' ? state.task.taskfile : state.task.resultfile;

  if (!fileName) {
    ElMessage.warning("文件不存在");
    return;
  }

  downloadTaskFile(state.task.id).then((response) => {
    // 提取文件名
    const filename = fileName.match(/[^/]+$/)[0];

    const url = window.URL.createObjectURL(new Blob([response]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }).catch(() => {
    ElMessage.error("下载文件失败");
  });
};

// 打开弹窗
const openDialog = (taskId) => {
  state.isShowDialog = true;
  state.task = null;
  state.operations = [];

  // 获取所有用户
  Axios.get("/backapi/user").then((res) => {
    state.users = res.data.allUser;
  }).catch(() => {
    ElMessage.error("获取用户列表失败");
  });

  // 获取任务详情
  getTaskDetail(taskId).then(res => {
    state.task = res.task;
    state.operations = res.operations;
  }).catch(() => {
    ElMessage.error("获取任务详情失败");
    closeDialog();
  });
};

// 关闭弹窗
const closeDialog = () => {
  state.isShowDialog = false;
};

// 暴露变量
defineExpose({
  openDialog
});
</script>

<style scoped lang="scss">
.task-detail-dialog-container {
  .task-detail {
    .task-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .label {
        margin-right: 5px;
      }

      .label + h2 {
        margin-right: auto;
      }
      .label {
        color: #606266;
        margin-right: 5px;
        font-weight: bold;
      }
      h2 {
        margin: 0;
        font-size: 20px;
      }
    }

    .task-info {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 20px;
      background-color: #f5f7fa;
      padding: 15px;
      border-radius: 4px;

      .info-item {
        width: 50%;
        margin-bottom: 10px;
        font-size: 14px;

        .label {
          color: #606266;
          margin-right: 5px;
          font-weight: bold;
        }
      }
    }

    .section-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #303133;
      border-left: 3px solid #409eff;
      padding-left: 10px;
    }

    .task-description {
      margin-bottom: 20px;

      .content {
        background-color: #f5f7fa;
        padding: 15px;
        border-radius: 4px;
        white-space: pre-line;
        line-height: 1.5;
      }
    }

    .task-files {
      margin-bottom: 20px;

      .file-list {
        background-color: #f5f7fa;
        padding: 15px;
        border-radius: 4px;

        .file-item {
          display: flex;
          align-items: center;
          margin-bottom: 10px;

          .file-name {
            margin-left: 8px;
            flex: 1;
          }
        }

        .no-files {
          color: #909399;
          font-style: italic;
        }
      }
    }

    .task-operations {
      .operation-content {
        .operator {
          font-weight: bold;
          margin-right: 8px;
        }
      }
    }
  }

  .loading-container {
    padding: 20px 0;
  }
}
</style>
